//
//  MusicViewController.m
//  LoveListen
//
//  Created by 王喆 on 15/7/2.
//  Copyright (c) 2015年 王喆. All rights reserved.
//

#import "MusicViewController.h"
#import "AFSoundManager.h"
#import "UIImageView+WebCache.h"
#import "DescriptionViewController.h"
#import "AFNetworking.h"
#import "DetailViewController.h"
#define kUrl @"http://app.9nali.com/935/tracks/%@?device=iPhone&version=1.1.5"
#import "MusicModel.h"
#import "DetailModel.h"

#import <AVFoundation/AVFoundation.h>

@interface MusicViewController ()
{
    BOOL _isPlay;
    
    
   
    AFHTTPRequestOperationManager *_manager;
    MusicModel * _model;
    NSMutableArray *_dataArr;
    int _index;

}
@property (assign, nonatomic) float rotationDuration;

@end

@implementation MusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 后台播放，第三步，设置 音频会话类型
    AVAudioSession *session = [AVAudioSession sharedInstance];
    // 类型是:播放和录音
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    // 而且要激活 音频会话
    [session setActive:YES error:nil];
    
    [self play];
    _isPlay = YES;
    [self startAnimation];
    [self creatButtonClick];
    [self addTaskWithUrl:[NSString stringWithFormat:kUrl,self.trackId]];
    
    //self.navigationController.navigationBarHidden = YES;
    //self.navigationController.navigationBar.hidden = YES;
    [self.lowImage sd_setImageWithURL:[NSURL URLWithString:self.coverLarge] placeholderImage:[UIImage imageNamed:@"me"]];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    NSDictionary *dict = @{@"title":self.title,@"coverLarge":self.coverLarge,@"isplay":@(_isPlay),@"playUrl64":self.playUrl64};
    
   // NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.title,@"title",self.playUrl64,@"playUrl64",@(_isPlay),@"isplay", nil];
    
   [center postNotificationName:@"change" object:self userInfo:dict];
   
    
    
   
    //self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
   // [_playButton setImage:[UIImage imageNamed:@"tabbar_pause_n"] forState:UIControlStateSelected];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = YES;

}



-(void)addTaskWithUrl:(NSString *)url{
    
    
    _manager =[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        _model = [[MusicModel alloc]init];
        
        [_model setValuesForKeysWithDictionary:dict];
        
        [self.TextButton setTitle:self.title forState:UIControlStateNormal];
        [self.TextButton addTarget:self action:@selector(TextButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        }
        
     
        
        
        
        
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
        
    }];
    
    
}


-(void)TextButtonClick:(UIButton *)button {
    DescriptionViewController *description = [[DescriptionViewController alloc]init];
    description.intro = _model.intro;
    [self.navigationController pushViewController:description animated:YES];
  //  [description setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
  //  [self presentViewController:description animated:YES completion:nil];
    
}


-(void)creatButtonClick{
     
    
        [_playButton addTarget:self action:@selector(playClick) forControlEvents:UIControlEventTouchUpInside];
    [_slider addTarget:self action:@selector(backOrForwardAudio:) forControlEvents:UIControlEventValueChanged];
    _slider.value = 0;
    
    
//    [_nextButton addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
//    [_upButotn addTarget:self action:@selector(upClick) forControlEvents:UIControlEventTouchUpInside];
}
-(void)play{
    
   
        
        
        [_playButton setImage:[UIImage imageNamed:@"tabbar_play_n"] forState:UIControlStateNormal];
        [[AFSoundManager sharedManager]startStreamingRemoteAudioFromURL:self.playUrl64 andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
            
            
            if (!error) {
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"mm:ss"];
                NSDate *startTimeData = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
                _startTime.text = [formatter stringFromDate:startTimeData];
                
                NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
                _overTime.text = [formatter stringFromDate:timeRemainingDate];
                
                _slider.value = percentage * 0.01;
                
                if (_isPlay == YES) {
                    [self.playButton setImage:[UIImage imageNamed:@"tabbar_pause_n"] forState:UIControlStateNormal];
                }
                
                
                
            } else {
                
                NSLog(@"There has been an error playing the remote file: %@", [error description]);
                
            }
            
            
            
        }];

        
    }
   
    
    



-(void)playClick{
    if (_isPlay == YES) {
        _isPlay = NO;
        [self.playButton setImage:[UIImage imageNamed:@"tabbar_play_n"] forState:UIControlStateNormal];
         [[AFSoundManager sharedManager]pause];
        
       }else{
        
    [self.playButton setImage:[UIImage imageNamed:@"tabbar_pause_n"] forState:UIControlStateNormal];
           
           _isPlay = YES;
           [[AFSoundManager sharedManager]resume];
        
    }
  }

#pragma mark  -滚动视图
-(void)startAnimation{
    [self.roundView sd_setImageWithURL:[NSURL URLWithString:self.coverLarge] placeholderImage:[UIImage imageNamed:@"medium_head_male_default"]];
    
    //Rotation 
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI *2 ];
    
    //default RotationDuration value
    if (self.rotationDuration == 0) {
        self.rotationDuration = 8;
    }
    
    rotationAnimation.duration = self.rotationDuration;
    rotationAnimation.repeatCount = FLT_MAX;
    rotationAnimation.cumulative = NO;
    [self.roundView.layer addAnimation:rotationAnimation forKey:nil];
    self.roundView.layer.cornerRadius = self.roundView.frame.size.width / 2;

    CFTimeInterval pausedTime = [self.roundView.layer timeOffset];
    self.roundView.layer.masksToBounds = YES;
    
    //self.roundView.layer.cornerRadius = 200;
    self.roundView.layer.speed = 0.2;
    self.roundView.layer.timeOffset = 0.0;
    self.roundView.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [self.roundView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    self.roundView.layer.beginTime = timeSincePause;
    

}







    
    


-(void)backOrForwardAudio:(UISlider *)slider{
    [[AFSoundManager sharedManager]moveToSection:slider.value];
    
    
    
}

-(void)resiveArr:(NSMutableArray *)arr index:(int) index{
    _dataArr = [[NSMutableArray alloc]initWithArray:arr];
    _index = index;
}
- (IBAction)upButton:(id)sender {
    if (_index > 0) {
        _index -=1;
        DetailModel *model = _dataArr[_index];
        self.playUrl64 = model.playUrl64;
        self.coverLarge = model.coverLarge;
        self.title = model.title;
        [self.lowImage sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:[UIImage imageNamed:@"me"]];
        [self play];
        [self startAnimation];
        
        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"已到达第一曲" message:@"" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        alertView.alertViewStyle = UIAlertActionStyleDefault;
        [alertView show];
    
    }
    
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)nextButton:(id)sender {
    if (_index < _dataArr.count-1) {
        _index+=1;
        DetailModel *model = _dataArr[_index];
        self.playUrl64 = model.playUrl64;
        self.coverLarge = model.coverLarge;
        self.title = model.title;
        [self.lowImage sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:[UIImage imageNamed:@"me"]];
        [self play];
        [self startAnimation];

        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"专辑播放完毕" message:@"" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        alertView.alertViewStyle = UIAlertActionStyleDefault;
        [alertView show];
    
    
    }
    
    
}

- (IBAction)popButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
   // [self dismissViewControllerAnimated:YES completion:nil];
    
   
}

- (IBAction)jianjieButton:(id)sender {
    DescriptionViewController *description = [[DescriptionViewController alloc]init];
    description.intro = _model.intro;
    
  //  [self presentViewController:description animated:YES completion:nil];
    
    
    [self.navigationController pushViewController:description animated:YES];
    
}
@end
